//
//  GizManage.m
//  steamRoom
//
//  Created by 安建伟 on 2019/7/3.
//  Copyright © 2019 com.thingcom. All rights reserved.
//

#import "GizManage.h"

#import <SystemConfiguration/CaptiveNetwork.h>

static GizManage *_gizManage = nil;

@implementation GizManage

+ (instancetype)shareInstance{
    if (_gizManage == nil) {
        _gizManage = [[self alloc] init];
    }
    return _gizManage;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t oneToken;
    
    dispatch_once(&oneToken, ^{
        if (_gizManage == nil) {
            _gizManage = [super allocWithZone:zone];
        }
    });
    
    return _gizManage;
}

#pragma mark - set
- (void)setGizDevice:(GizWifiDevice *)device{
    if (self.device) {
        self.device.delegate = nil;
    }
    self.device = device;
    self.device.delegate = self;
    if (self.device.isSubscribed) {
        return;
    }
    [self.device setSubscribe:NULL subscribed:YES];
}

#pragma mark - Giz Control

/**
 *  写数据点的值到设备
 *
 *  @param dataPoint 标识数据点的枚举值
 *  @param value     数据点值
 */
- (void)writeDataPoint:(DeviceDataPoint)dataPoint value:(id)value
{
    NSDictionary *data = nil;
    switch (dataPoint) {
        case Device_SystemPower:
        {
            self.key_SystemPower = [value boolValue];
            data = @{Data__Attr_SystemPower: value};
            break;
        }
        case Device_SystemFan:
        {
            self.key_SystemFan = [value boolValue];
            data = @{Data__Attr_SystemFan: value};
            break;
        }
        case Device_OneLight:
        {
            self.key_OneLight = value;
            data = @{Data__Attr_SystemLight: [[self dataProcessing:value twoValue:self.key_TwoLight] hexToBytes]};
            NSLog(@"key_OneLight%@",data);
            break;
        }
        case Device_TwoLight:
        {
            self.key_TwoLight = value;
            data = @{Data__Attr_SystemLight: [[self dataProcessing:self.key_OneLight twoValue:value] hexToBytes]};
            NSLog(@"key_TwoLight%@",data);
            break;
        }
        case Device_SaunaStateTimeTemp:
        {
            self.key_SaunaStateTimeTemp = value;
            data = @{Data__Attr_SaunaStateTimeTemp: [self.key_SaunaStateTimeTemp hexToBytes]};
            break;
        }
        case Device_FMBT_StateFreqVol:
        {
            self.key_FMBT_StateFreqVol = value;
            data = @{Data__Attr_FMBT_StateFreqVol: [self.key_FMBT_StateFreqVol hexToBytes]};
            break;
        }
        default:
            NSLog(@"Error: write invalid datapoint, skip.");
            return;
    }
    NSLog(@"Write data: %@", data);
    [self.device write:data withSN:0];
}

#pragma mark - read Action
/**
 *  从数据点集合中获取数据点的值
 *
 *  @param dataMap 数据点集合
 */
- (void)readDataPointsFromData:(NSDictionary *)attrStatus
{
    // 读取普通数据点的值
    NSDictionary *data = [attrStatus valueForKey:@"data"];
    NSMutableArray *deviceDicArr = [[NSMutableArray alloc] init];
    [deviceDicArr addObject:[self readDataPoint:Device_SystemPower data:data]];
    [deviceDicArr addObject:[self readDataPoint:Device_SystemFan data:data]];
    [deviceDicArr addObject:[self readDataPoint:Device_ErrorImfor data:data]];
    [deviceDicArr addObject:[self readDataPoint:Device_RoomTemp data:data]];
    [deviceDicArr addObject:[self readDataPoint:Device_SaunaRunTime data:data]];
    [deviceDicArr addObject:[self readDataPoint:Device_OneLight data:data]];
    [deviceDicArr addObject:[self readDataPoint:Device_TwoLight data:data]];
    [deviceDicArr addObject:[self readDataPoint:Device_SaunaStateTimeTemp data:data]];
    [deviceDicArr addObject:[self readDataPoint:Device_FMBT_StateFreqVol data:data]];
    [deviceDicArr addObject:[self readDataPoint:Device_FMBT_16_Freq data:data]];
    
    NSDictionary *sendDataPointToRN = @{@"data":deviceDicArr};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"sendCustomEventNotification" object:nil userInfo:sendDataPointToRN];
}


/**
 *  获取普通数据点的各个数据点值
 *
 *  @param data 普通数据点集合
 */
- (NSDictionary *)readDataPoint:(DeviceDataPoint)dataPoint data:(NSDictionary *)data
{
    if(![data isKindOfClass:[NSDictionary class]])
    {
        NSLog(@"Error: could not read data, error data format.");
        return @{};
    }
    NSDictionary *deviceDic = [[NSDictionary alloc] init];
    switch (dataPoint) {
        case Device_SystemPower:
        {
            NSString *dataPointStr = [data valueForKey:Data__Attr_SystemPower];
            if (dataPointStr == nil) {
                return @{};
            }
            self.key_SystemPower = dataPointStr.boolValue;
            deviceDic =@{@"deviceName":@"Device_SystemPower",@"value":[NSString stringWithFormat:@"%d",self.key_SystemPower]};
            
            break;
        }
        case Device_SystemFan:
        {
            NSString *dataPointStr = [data valueForKey:Data__Attr_SystemFan];
            if (dataPointStr == nil) {
                return @{};
            }
            self.key_SystemFan = dataPointStr.boolValue;
            deviceDic = @{@"deviceName":@"Device_SystemFan",@"value":[NSString stringWithFormat:@"%d",self.key_SystemFan]};
            
            break;
        }
        case Device_ErrorImfor:
        {
            NSString *dataPointStr = [data valueForKey:Data__Attr_ErrorImfor];
            if (dataPointStr == nil) {
                return @{};
            }
            self.key_ErrorImfor = dataPointStr.integerValue;
            deviceDic =@{@"deviceName":@"Device_ErrorImfor",@"value":dataPointStr};
            break;
        }
        case Device_RoomTemp:
        {
            NSString *dataPointStr = [data valueForKey:Data__Attr_RoomTemp];
            if (dataPointStr == nil) {
                return @{};
            }
            self.key_RoomTemp = dataPointStr.integerValue;
            deviceDic = @{@"deviceName":@"Device_RoomTemp",@"value":dataPointStr};
            break;
        }
        case Device_SaunaRunTime:
        {
            NSString *dataPointStr = [data valueForKey:Data__Attr_SaunaRunTime];
            if (dataPointStr == nil) {
                return @{};
            }
            self.key_SaunaRunTime = dataPointStr.integerValue;
            deviceDic = @{@"deviceName":@"Device_SaunaRunTime",@"value":dataPointStr};
            break;
        }
        case Device_OneLight:
        {
            NSData *dataPointStr = [data valueForKey:Data__Attr_SystemLight];
            if (dataPointStr == nil) {
                return @{};
            }
            {
                switch ([[NSString hexStrByData:dataPointStr] integerValue]) {
                    case 0:
                        self.key_OneLight = @"0";
                        self.key_TwoLight = @"0";
                        break;
                    case 1:
                        self.key_OneLight = @"1";
                        self.key_TwoLight = @"0";
                        break;
                    case 2:
                        self.key_OneLight = @"0";
                        self.key_TwoLight = @"1";
                        break;
                    default:
                        self.key_OneLight = @"1";
                        self.key_TwoLight = @"1";
                        break;
                }
                
            }
            deviceDic = @{@"deviceName":@"Device_OneLight",@"value":self.key_OneLight};
            break;
        }
        case Device_TwoLight:
        {
            NSData *dataPointStr = [data valueForKey:Data__Attr_SystemLight];
            if (dataPointStr == nil) {
                return @{};
            }
            {
                switch ([[NSString hexStrByData:dataPointStr] integerValue]) {
                    case 0:
                        self.key_OneLight = @"0";
                        self.key_TwoLight = @"0";
                        break;
                    case 1:
                        self.key_OneLight = @"1";
                        self.key_TwoLight = @"0";
                        break;
                    case 2:
                        self.key_OneLight = @"0";
                        self.key_TwoLight = @"1";
                        break;
                    default:
                        self.key_OneLight = @"1";
                        self.key_TwoLight = @"1";
                        break;
                }
                NSLog(@"获取两个灯状态 %@%@ %@",dataPointStr,self.key_OneLight,self.key_TwoLight);
            }
            deviceDic = @{@"deviceName":@"Device_TwoLight",@"value":self.key_TwoLight};
            break;
        }
        case Device_SaunaStateTimeTemp:
        {
            NSData *dataPointStr = [data valueForKey:Data__Attr_SaunaStateTimeTemp];
            if (dataPointStr == nil) {
                return @{};
            }
            self.key_SaunaStateTimeTemp = [NSString hexStrByData:dataPointStr];
            deviceDic =@{@"deviceName":@"Device_SaunaStateTimeTemp",@"value":self.key_SaunaStateTimeTemp};
            break;
        }
        case Device_FMBT_StateFreqVol:
        {
            NSData *dataPointStr = [data valueForKey:Data__Attr_FMBT_StateFreqVol];
            if (dataPointStr == nil) {
                return @{};
            }
            self.key_FMBT_StateFreqVol = [NSString hexStrByData:dataPointStr];
            deviceDic =@{@"deviceName":@"Device_FMBT_StateFreqVol",@"value":self.key_FMBT_StateFreqVol};
            break;
        }
        case Device_FMBT_16_Freq:
        {
            NSData *dataPointStr = [data valueForKey:Data__Attr_FMBT_16_Freq];
            if (dataPointStr == nil) {
                return @{};
            }
            self.key_FMBT_16_Freq = [NSString hexStrByData:dataPointStr];
            deviceDic =  @{@"deviceName":@"Device_FMBT_16_Freq",@"value":self.key_FMBT_16_Freq};
            break;
        }
        default:
            NSLog(@"Error: read invalid datapoint, skip.");
            break;
    }
    return deviceDic;
    
}

/**
 *  初始化设备  ，即将设备的值都设为默认值
 */
- (void)initDevice
{
    // 重新设置设备
    self.key_SystemPower = NO;
    self.key_SystemFan = NO;
    self.key_ErrorImfor = 0;
    self.key_RoomTemp = 0;
    self.key_SaunaRunTime = 0;
    self.key_OneLight = @"";
    self.key_TwoLight = @"";
    self.key_SaunaStateTimeTemp = @"";
    self.key_FMBT_StateFreqVol = @"";
    self.key_FMBT_16_Freq = @"";
}
//判断设备类型
- (DeviceDataPoint)judgeDeviceNameWith:(NSString *)deviceName{
    if ([deviceName isEqualToString:@"Device_SystemFan"]) {
        return Device_SystemFan;
    }
    if ([deviceName isEqualToString:@"Device_ErrorImfor"]) {
        return Device_ErrorImfor;
    }
    if ([deviceName isEqualToString:@"Device_RoomTemp"]) {
        return Device_RoomTemp;
    }
    if ([deviceName isEqualToString:@"Device_SaunaRunTime"]) {
        return Device_SaunaRunTime;
    }
    if ([deviceName isEqualToString:@"Device_SaunaStateTimeTemp"]) {
        return Device_SaunaStateTimeTemp;
    }
    if ([deviceName isEqualToString:@"Device_FMBT_StateFreqVol"]) {
        return Device_FMBT_StateFreqVol;
    }
    if ([deviceName isEqualToString:@"Device_FMBT_16_Freq"]){
        return Device_FMBT_16_Freq;
    }
    if ([deviceName isEqualToString:@"Device_OneLight"]) {
        return Device_OneLight;
    }
    if ([deviceName isEqualToString:@"Device_TwoLight"]) {
        return Device_TwoLight;
    }
    return Device_SystemPower;
}

- (NSString *)dataProcessing:(NSString *) oneValue twoValue:(NSString *) twoValue{
    if ([oneValue isEqualToString:@"0"] && [twoValue isEqualToString:@"0"]) {
        return @"00";
    }else if ([oneValue isEqualToString:@"0"] && [twoValue isEqualToString:@"1"]){
        return @"01";
    }else if ([oneValue isEqualToString:@"1"] && [twoValue isEqualToString:@"0"]){
        return @"02";
    }else{
        return @"03";
    }
}

#pragma mark - Giz delegate
- (void)device:(GizWifiDevice *)device didSetSubscribe:(NSError *)result isSubscribed:(BOOL)isSubscribed{
    NSLog(@"subscribeResult---- %@",result);
}

//获取设备数据点状态回调
- (void)device:(GizWifiDevice * _Nonnull)device didReceiveAttrStatus:(NSError * _Nonnull)result attrStatus:(NSDictionary * _Nullable)attrStatus adapterAttrStatus:(NSDictionary * _Nullable)adapterAttrStatus withSN:(NSNumber * _Nullable)sn
{
    //读取设备状态
    if (result.code == GIZ_SDK_SUCCESS)
    {
        NSDictionary *data = [attrStatus valueForKey:@"data"];
        NSLog(@"查询上报的信息。。。%@",attrStatus);
        if(data != nil && [data count] != 0)
        {
            // 读取所有数据点值
            [[GizManage shareInstance] readDataPointsFromData:attrStatus];
        }
        //[[NSNotificationCenter defaultCenter] postNotificationName:@"sendCustomEventNotification" object:nil userInfo:data];
    }
}

#pragma 获取设备当前连接的WIFI的SSID
+ (NSString *)getCurrentWifi{
    
    NSString * wifiName = @"";
    CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();
    
    if (!wifiInterfaces) {
        wifiName = @"";
    }
    
    NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;
    
    for (NSString *interfaceName in interfaces) {
        
        CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));
        if (dictRef) {
            
            NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
            wifiName = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
            CFRelease(dictRef);
        }
    }
    
    //CFRelease(wifiInterfaces);
    return wifiName;
}


@end
